package org.openzip.openzip.gui.util.checkBox;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.HashSet;

/**
 * This class represents a inner state of a checkBox (without the JComponent
 * graphics). It serves an a "model" for a checkbox, if we need one, but do not
 * need to paint it or otherwise treat it as a graphical component.
 */
public class BasicCheckBoxModel
{
	//whether the checkbox is selected
	private boolean selected;
	//collection of action listeners
	private Collection<ActionListener> actionListeners;
	
	/**
	 * Constructor.
	 * 
	 * @param selected
	 *           Initial state of the checkbox
	 */
	public BasicCheckBoxModel(boolean selected){
		this.selected = selected;
		actionListeners = new HashSet<ActionListener>();
	}
	
	public BasicCheckBoxModel(){
		this(false);
	}

	/**
	 * Add an actionListener to this checkbox.
	 */
	public void addActionListener(ActionListener a){
		actionListeners.add(a);
	}
	
	/**
	 * Removes an actionListener from this checkbox.
	 */
	public void removeActionListener(ActionListener a){
		actionListeners.remove(a);
	}
	
	/**
	 * Fires an actionPerformed event with this checkbox as a source.
	 */
	protected void fireActionPerformed(){
		ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "");
		for(ActionListener listener : actionListeners){
			listener.actionPerformed(e);
		}
	}
	
	/**
	 * Gets if the checkbox is selected.
	 */
	public boolean isSelected(){
		return selected;
	}
	
	/**
	 * Sets the selected property and fires actionPerfomed if the property
	 * actually changed.
	 * 
	 * @param b
	 *           New selection state.
	 */
	public void setSelected(boolean b){
		boolean willFire = selected != b;
		selected = b;
		if(willFire){
			fireActionPerformed();
		}
	}
}
